import React, {Component} from 'react'
import {Popover, Spin, Avatar, Button, Icon} from 'antd'
import propTypes from 'prop-types'
import {get} from '../../common/js/utils'
import {withRouter} from 'react-router-dom'
import './index.scss'

@withRouter
class UserCard extends Component {

  state = {
    loading: false,
    userInfo: {}
  }

  getInfo = () => {
    const {_id} = this.props
    get('api/users/info', {_id}, loading => this.setState({loading})).then(res => {
      if (res.result === 1) {
        this.setState({userInfo: res.data})
      }
    })
  }

  onVisibleChange = (visible) => {
    if (visible) {
      this.getInfo()
    }
  }

  render() {
    const {placement, history} = this.props
    const {loading, userInfo} = this.state
    return (
      <Popover
        placement={placement}
        trigger="hover"
        onVisibleChange={this.onVisibleChange}
        overlayClassName="user-card-popover"
        content={
          <Spin
            spinning={loading}
            tip="加载中..."
          >
            <div
              className="user-card"
            >
              <div
                className="bg"
                style={{
                  backgroundImage: `url(${userInfo.face})`
                }}
              />
              <div className="top">
                <Avatar
                  src={userInfo.face}
                  size={70}
                />
                <p className="nick">
                  {
                    userInfo.sex === 1 ?
                      <Icon className="nan" type="man" /> :
                      <Icon className="nv" type="woman" />
                  }
                  <span style={{margin: '0 0 0 5px'}}>{userInfo.nickname}</span>
                </p>
                <p className="introduce">个人简介：{userInfo.introduce || '还没有个人简介哦'}</p>
              </div>
              <div className="action">
                <Button
                  size="small"
                  onClick={e => history.push(`/user?_id=${userInfo._id}`)}
                >进入主页</Button>
              </div>
            </div>
          </Spin>
        }
      >
        {this.props.children}
      </Popover>
    )
  }
}

UserCard.propTypes = {
  placement: propTypes.oneOf(['left', 'right', 'top', 'bottom', 'bottomRight', 'topLeft', 'topRight', 'bottomLeft', 'leftTop', 'leftBottom', 'rightTop', 'rightBottom', undefined]),
  _id: propTypes.string.isRequired
}

UserCard.defaultProps = {
  placement: undefined
}

export {UserCard}
